<?php
namespace Admin\Controller;
use Lib\Api\AgentSettlementApi;
use Think\Controller;
class AgentSettlementController extends Controller {
    private $modelName = 'AgentSettlement';

    public function index(){
        $this->display();
    }

    public function tolist() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $organization_id = session('admin_id');

        $field = "a.*, b.name, b.mobile_phone";

        $where["a.state"] = array("eq", 1);
        $where['_string'] = '(c.organization_id='.$organization_id.' and DATE_FORMAT(c.datetime, "%Y-%m-%d %H:%i:%s") <= DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")) ';
        $left = 'left join fs_agent b on b.id = a.agent_id';
        $left .= ' left join fs_agent_belong c on c.agent_id = b.id';

        $AGENTCONFIG = C('AGENTCONFIG');
        for($i=1; $i<(count($AGENTCONFIG)-2); $i++) {
            $field .= ',ifnull(o'.$i.'.name, "--") as '.$AGENTCONFIG[$i]['field'];
            $left .= ' left join fs_agent_belong ob'.$i.' on ob'.$i.'.agent_id = b.id and ob'.$i.'.organization_level = '.$i;
            $left .= ' left join fs_organization o'.$i.' on o'.$i.'.id = ob'.$i.'.organization_id';
        }

        $list = AgentSettlementApi::getList($where, $left, $page_num, $page_size, $field, 'a.settlement_date desc, a.id asc');
        $total = AgentSettlementApi::getTotal($where, $left);
        $user_list = pageHelper($page_size, $page_num, $list, $total);
        $rel['data'] = $user_list;

        $sum_settlement_money = AgentSettlementApi::getSum($where, "a.settlement_money", $left);
        if(empty($sum_settlement_money)) {
            $sum_settlement_money = 0;
        }
        $rel["sum_settlement_money"] = sprintf("%.2f", $sum_settlement_money);

        $sum_total_fee = AgentSettlementApi::getSum($where, "a.total_fee", $left);
        if(empty($sum_total_fee)) {
            $sum_total_fee = 0;
        }
        $rel["sum_total_fee"] = sprintf("%.2f", $sum_total_fee);

        $this->ajaxReturn($rel);
    }
}